﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Xsl;
using INFSWA01___Computerwinkel.Service;
using INFSWA01___Computerwinkel.Code.Objects;
using System.Xml.Linq;

namespace INFSWA01___Computerwinkel
{
    public partial class Main : Form
    {
        private bool isXMLInOrder = true;
        private List<Artikel> artikelen;
        private List<Artikel> artikelenReading;
        private VoorraadService vs;

        public Main()
        {
            InitializeComponent();
            textBox1.ReadOnly = true;
            textBox1.Multiline = false;
            textBox2.ReadOnly = true;
            textBox2.Multiline = false;
            textBox3.ReadOnly = true;
            textBox3.Multiline = false;
            textBox4.ReadOnly = true;
            textBox4.Text = "Selecteer het XML en XSD schema en klik op knop 'Valideer'!";
            textBox9.ReadOnly = true;
            artikelen = new List<Artikel>();
            artikelenReading = new List<Artikel>();
            vs = new VoorraadService();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // Maak / configureer de openfiledialog aan.
            
            openFileDialog1.Title = "Selecteer het XML document!";
            openFileDialog1.Filter = "XML document (*.xml)|*.xml|All files (*.*)|*.*";
            openFileDialog1.Multiselect = false;
            openFileDialog1.CheckFileExists = true;
            openFileDialog1.CheckPathExists = true;
            openFileDialog1.ShowDialog();
        }

        private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
        {
            // Handel de actie van het geselecteerde xml document af.
            textBox1.Text = openFileDialog1.FileName;

            Stream stream = null;
            if ((stream = openFileDialog1.OpenFile()) != null)
            {

            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            // Openfiledialog 2 voor xml schema.
            openFileDialog2.Title = "Selecteer het XML schema!";
            openFileDialog2.Filter = "XSD schema (*.xsd)|*.xsd|All files (*.*)|*.*";
            openFileDialog2.Multiselect = false;
            openFileDialog2.CheckFileExists = true;
            openFileDialog2.CheckPathExists = true;
            openFileDialog2.ShowDialog();
        }

        private void openFileDialog2_FileOk(object sender, CancelEventArgs e)
        {
            // Handel de actie van het geselecteerde xml schema af.
            textBox2.Text = openFileDialog2.FileName;

            Stream stream = null;
            if ((stream = openFileDialog2.OpenFile()) != null)
            {
                
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            // XSLT document

            if (!checkIfDocumentsAreSelected())
            {
                MessageBox.Show("Selecteer a.u.b. eerst het XML en XSD schema in het tabblad: 'Controleer XML m.b.v. XSD'", "Ontbrekende documenten", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                openFileDialog3.Title = "Selecteer het XSLT document!";
                openFileDialog3.Filter = "XSLT schema (*.xslt)|*.xslt|All files (*.*)|*.*";
                openFileDialog3.Multiselect = false;
                openFileDialog3.CheckFileExists = true;
                openFileDialog3.CheckPathExists = true;
                openFileDialog3.ShowDialog();
            }
        }

        private void openFileDialog3_FileOk(object sender, CancelEventArgs e)
        {
            textBox3.Text = openFileDialog3.FileName;

            Stream stream = null;
            if ((stream = openFileDialog3.OpenFile()) != null)
            {

            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            // Valideren van xml m.b.v. schema.
            validerenXMLXSD();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            // Toont de html output van de xml in combinatie met de xsd en xslt.
            if (openFileDialog3.FileName.Equals("openFileDialog3"))
            {
                MessageBox.Show("Selecteer a.u.b. eerst het XSLT document in het tabblad: 'Toon XML m.b.v. XSLT'", "Ontbrekende documenten", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                var myXslTrans = new XslCompiledTransform();
                myXslTrans.Load(openFileDialog3.FileName);
                myXslTrans.Transform(openFileDialog1.FileName, "result.html");

                string directory = AppDomain.CurrentDomain.BaseDirectory;
                directory += @"result.html";
                Uri url = new Uri(directory);
                webBrowser1.Url = url;
                webBrowser1.Refresh();
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            // Maak XML document aan.
            string artikel_naam = textBox5.Text;
            string prijs = textBox6.Text;
            string merk = textBox7.Text;
            string type = textBox8.Text;

            // Roep de ArtikelService aan die de models vult en uiteindelijk het XML bestand maakt.
            artikelen.Add(vs.CreateArtikel((artikelen.Count() + 1), artikel_naam, prijs, merk, type));
            label10.Text = "Aantal artikelen in lijst:" + artikelen.Count();
        }

        private void button8_Click(object sender, EventArgs e)
        {
            if (artikelen.Count() > 0)
            {
                vs.CreateXMLFromList(artikelen);
            }
            else
            {
                MessageBox.Show("Voeg eerst een artikel toe aan de lijst", "Geen artikelen in de lijst!",MessageBoxButtons.OK,MessageBoxIcon.Warning);
            }
        }

        private void button7_Click(object sender, EventArgs e)
        {
            openFileDialog4.Title = "Selecteer het XML document!";
            openFileDialog4.Filter = "XML document (*.xml)|*.xml|All files (*.*)|*.*";
            openFileDialog4.Multiselect = false;
            openFileDialog4.CheckFileExists = true;
            openFileDialog4.CheckPathExists = true;
            openFileDialog4.ShowDialog();           
        }

        private void openFileDialog4_FileOk(object sender, CancelEventArgs e)
        {
            textBox9.Text = openFileDialog4.FileName;

            Stream stream = null;
            if ((stream = openFileDialog4.OpenFile()) != null)
            {
                XDocument doc = XDocument.Load(stream);
                var artikelen = doc.Descendants("Artikel");

                foreach (var artikel in artikelen)
                {
                    int id = int.Parse((string)((XElement)artikel).FirstAttribute.Value);
                    string naam = (string)((XElement)artikel).Element("Naam");
                    string prijs = (string)((XElement)artikel).Element("Prijs");
                    string merk = (string)((XElement)artikel).Element("Merk");
                    string type = (string)((XElement)artikel).Element("Type");

                    artikelenReading.Add(vs.CreateArtikel(id, naam, prijs,merk,type));
                }
            }
        }

        private void validerenXMLXSD()
        {
            if (!checkIfDocumentsAreSelected())
            {
                MessageBox.Show("Selecteer a.u.b. eerst het XML en XSD schema in het tabblad: 'Controleer XML m.b.v. XSD'","Ontbrekende documenten",MessageBoxButtons.OK,MessageBoxIcon.Warning);
            }
            else
            {
                VerifyXmlFile(openFileDialog1.FileName);
            }
        }

        private void VerifyXmlFile(string path)
        {

            // configure the xmlreader validation to use inline schema.
            XmlReaderSettings config = new XmlReaderSettings();
            config.ValidationType = ValidationType.Schema;
            config.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
            config.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
            config.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
            config.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);

            // Get the XmlReader object with the configured settings.
            XmlReader reader = XmlReader.Create(path, config);

            // Clear the textbox
            textBox4.Text = "";

            // Parsing the file will cause the validation to occur.
            while (reader.Read()) ;

            if (isXMLInOrder)
            {
                textBox4.Text = "XMl is succesvol gecontroleerd m.b.v. het XSD schema.";
            }
        }

        private void ValidationCallBack(object sender, ValidationEventArgs vea)
        {
            isXMLInOrder = false;

            if (vea.Severity == XmlSeverityType.Warning)
            {
                textBox4.Text += ("Warning: Matching schema not found.  No validation occurred.: " + vea.Message + "\r\n");
            }
            else
            {
                textBox4.Text += ("Validation error: " + vea.Message + "\r\n");
            }
        }

        private bool checkIfDocumentsAreSelected()
        {
            if (openFileDialog1.FileName.Equals("openFileDialog1") || openFileDialog2.FileName.Equals("openFileDialog2"))
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        private void button9_Click(object sender, EventArgs e)
        {
            Uri url = new Uri("c:/artikelen.xml");
            webBrowser2.Url = url;
            webBrowser2.Refresh();
        }
    }
}